using System;
using System.Collections.Generic;
using System.Linq;

namespace TXK
{
    /// <summary>
    /// Float类型转换库
    /// </summary>
    public class FloatLib
    {
        /// <summary>
        /// 将字节数组中某4个字节转换成Float类型
        /// </summary>
        /// <param name="source"></param>
        /// <param name="start"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static float GetFloatFromByteArray(byte[] source, int start = 0, DataFormat type = DataFormat.ABCD)
        {
            byte[] array = ByteArrayLib.Get4ByteArray(source, start, type);
            return (array == null) ? 0f : BitConverter.ToSingle(array, 0);
        }

        /// <summary>
        /// 将字节数组转换成Float数组
        /// </summary>
        /// <param name="source"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static float[] GetFloatArrayFromByteArray(byte[] source, DataFormat type = DataFormat.ABCD)
        {
            float[] array = new float[source.Length / 4];
            for (int i = 0; i < source.Length / 4; i++)
            {
                array[i] = GetFloatFromByteArray(source, 4 * i, type);
            }
            return array;
        }

        /// <summary>
        /// 将Float字符串转换成单精度浮点型数组
        /// </summary>
        /// <param name="val">Float字符串</param>
        /// <param name="spilt">分隔符</param>
        /// <returns>单精度浮点型数组</returns>
        public static float[] GetFloatArrayFromString(string val, char spilt = ' ')
        {
            val = val.Trim();
            List<float> list = new List<float>();
            if (val.Contains(spilt))
            {
                string[] array = val.Split(new char[1] { spilt }, StringSplitOptions.RemoveEmptyEntries);
                string[] array2 = array;
                foreach (string text in array2)
                {
                    list.Add(Convert.ToSingle(text.Trim()));
                }
            }
            else
            {
                list.Add(Convert.ToSingle(val.Trim()));
            }
            return list.ToArray();
        }
    }
}
